import React, { useState, useRef } from "react";
import {
  Card,
  Input,
  Button,
  message,
  Layout,
  Menu,
  Modal,
  Upload,
} from "antd";
import ReactMarkdown from "react-markdown";
import {
  SaveOutlined,
  EyeOutlined,
  PlusOutlined,
  DeleteOutlined,
  FileTextOutlined,
  UploadOutlined,
  ClockCircleOutlined,
  EditOutlined,
} from "@ant-design/icons";
import type { UploadChangeParam } from "antd/es/upload";
import type { RcFile } from "rc-upload/lib/interface";
import "./style.css";

const { TextArea } = Input;
const { Sider, Content } = Layout;

interface Article {
  id: string;
  title: string;
  content: string;
  createdAt: Date;
  updatedAt: Date;
}

const defaultMd = `# 新建文章\n\n这是一个 **Markdown** 编辑器示例。\n\n- 支持实时预览\n- 支持保存\n- 支持图片上传\n\n> 你可以在左侧编辑，在右侧实时预览。`;

const ArticleManage: React.FC = () => {
  const [articles, setArticles] = useState<Article[]>([
    {
      id: "1",
      title: "新建文章",
      content: defaultMd,
      createdAt: new Date(),
      updatedAt: new Date(),
    },
  ]);
  const [currentId, setCurrentId] = useState("1");
  const [title, setTitle] = useState("新建文章");
  const [content, setContent] = useState(defaultMd);
  const [saving, setSaving] = useState(false);
  const editorRef = useRef<HTMLTextAreaElement>(null);

  // 切换文章
  const handleSelect = (id: string) => {
    const art = articles.find((a) => a.id === id);
    if (art) {
      setCurrentId(id);
      setTitle(art.title);
      setContent(art.content);
    }
  };

  // 新建文章
  const handleNew = () => {
    const newId = Date.now().toString();
    const newArticle: Article = {
      id: newId,
      title: "新建文章",
      content: defaultMd,
      createdAt: new Date(),
      updatedAt: new Date(),
    };
    setArticles([newArticle, ...articles]);
    setCurrentId(newId);
    setTitle(newArticle.title);
    setContent(newArticle.content);
  };

  // 删除文章
  const handleDelete = (id: string) => {
    Modal.confirm({
      title: "确认删除",
      content: "删除后无法恢复，确定要删除吗？",
      onOk: () => {
        const remain = articles.filter((a) => a.id !== id);
        setArticles(remain);
        if (remain.length > 0) {
          const first = remain[0];
          setCurrentId(first.id);
          setTitle(first.title);
          setContent(first.content);
        } else {
          handleNew();
        }
        message.success("删除成功");
      },
    });
  };

  // 保存文章（预留云端接口）
  const handleSave = async () => {
    if (!title.trim()) {
      message.warning("请输入文章标题");
      return;
    }
    setSaving(true);
    // TODO: 可在此调用后端保存接口
    setArticles((prev) =>
      prev.map((a) =>
        a.id === currentId ? { ...a, title, content, updatedAt: new Date() } : a
      )
    );
    setTimeout(() => {
      setSaving(false);
      message.success("文章已保存（本地模拟）");
    }, 600);
  };

  // 图片上传并插入到光标处
  const handleImageUpload = (info: UploadChangeParam) => {
    if (info.file.status === "done") {
      // 本地预览
      const file = info.file.originFileObj as RcFile;
      const url = URL.createObjectURL(file);
      insertImage(url);
      message.success("图片已插入");
    }
  };

  // 插入图片 Markdown 语法到光标处
  const insertImage = (url: string) => {
    const textarea = editorRef.current;
    if (!textarea) return;
    const start = textarea.selectionStart;
    const end = textarea.selectionEnd;
    const before = content.slice(0, start);
    const after = content.slice(end);
    const md = `![图片](${url})`;
    const newContent = before + md + after;
    setContent(newContent);
    setTimeout(() => {
      textarea.focus();
      textarea.selectionStart = textarea.selectionEnd = start + md.length;
    }, 0);
  };

  // 格式化日期
  const formatDate = (date: Date): string => {
    return new Intl.DateTimeFormat("zh-CN", {
      month: "short",
      day: "numeric",
      hour: "2-digit",
      minute: "2-digit",
    }).format(date);
  };

  // 文章列表菜单项
  const menuItems = articles.map((a) => ({
    key: a.id,
    icon: <FileTextOutlined />,
    label: (
      <div className="article-menu-item">
        <span className="article-menu-title">{a.title}</span>
        <div className="article-menu-meta">
          <span className="article-menu-time">
            <ClockCircleOutlined /> {formatDate(a.updatedAt)}
          </span>
          <span className="article-menu-word-count">{a.content.length} 字</span>
        </div>
        <Button
          type="text"
          size="small"
          icon={<DeleteOutlined />}
          onClick={(e) => {
            e.stopPropagation();
            handleDelete(a.id);
          }}
          className="delete-btn"
          title="删除文章"
        />
      </div>
    ),
  }));

  return (
    <Layout className="article-layout">
      <Sider width={280} className="article-sider">
        <div className="sider-header">
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={handleNew}
            block
          >
            新建文章
          </Button>
        </div>
        <div className="article-list-header">
          <span>我的文章 ({articles.length})</span>
        </div>
        <Menu
          mode="inline"
          selectedKeys={[currentId]}
          items={menuItems}
          onClick={({ key }) => handleSelect(key)}
          className="article-menu"
        />
      </Sider>
      <Content className="article-content">
        <Card
          title={
            <div className="article-card-header">
              <span className="article-card-title">文章管理</span>
              <span className="article-card-subtitle">
                管理和编辑您的Markdown文章
              </span>
            </div>
          }
          className="article-manage-card"
        >
          <div className="article-header">
            <Input
              placeholder="请输入文章标题"
              value={title}
              onChange={(e) => setTitle(e.target.value)}
              className="article-title-input"
              maxLength={60}
              prefix={<EditOutlined style={{ color: "#bbb" }} />}
            />
            <div className="article-actions">
              <Upload
                showUploadList={false}
                accept="image/*"
                customRequest={({ onSuccess }) => {
                  if (onSuccess) {
                    onSuccess("ok");
                  }
                }}
                onChange={handleImageUpload}
              >
                <Button icon={<UploadOutlined />}>插入图片</Button>
              </Upload>
              <Button
                type="primary"
                icon={<SaveOutlined />}
                onClick={handleSave}
                loading={saving}
              >
                保存
              </Button>
            </div>
          </div>
          <div className="article-main">
            <div className="article-editor">
              <TextArea
                ref={editorRef}
                value={content}
                onChange={(e) => setContent(e.target.value)}
                rows={20}
                placeholder="请输入 Markdown 内容..."
                className="md-textarea"
              />
            </div>
            <div className="article-preview">
              <div className="preview-header">
                <EyeOutlined /> 预览
              </div>
              <div className="preview-body">
                <ReactMarkdown>{content}</ReactMarkdown>
              </div>
            </div>
          </div>
        </Card>
      </Content>
    </Layout>
  );
};

export default ArticleManage;
